package com.jse.io.nio.network.old.muti.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

public class KnockKnockClient {
	public static final Logger mylog = Logger.getLogger(KnockKnockClient.class);
	
	public static void main(String[] args) throws IOException {

		// if (args.length != 2) {
		// System.err.println("Usage: java EchoClient <host name> <port
		// number>");
		// System.exit(1);
		// }
		//
		// String hostName = args[0];
		// int portNumber = Integer.parseInt(args[1]);

		InetAddress inetAddress = InetAddress.getLocalHost();
		try (Socket kkSocket = new Socket(inetAddress, 99);
				PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
				BufferedReader in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));) {
			BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
			String fromServer;
			String fromUser;

			while ((fromServer = in.readLine()) != null) {
				System.out.println("Server: " + fromServer);
				if (fromServer.equals("Bye."))
					break;

				fromUser = stdIn.readLine();
				if (fromUser != null) {
					System.out.println("Client: " + fromUser);
					out.println(fromUser);
				}
			}
		} catch (UnknownHostException e) {
			mylog.debug("Don't know about host " + inetAddress.getHostAddress());
			System.exit(1);
		} catch (IOException e) {
			mylog.debug("Couldn't get I/O for the connection to " + inetAddress.getHostAddress());
			System.exit(1);
		}
	}
}
